package com.cn.esermis.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.cn.esermis.model.BaseUser;

import javax.servlet.http.HttpServletRequest;

public class TokenUtils {

    private static final String AUTH_HEADER = "Authorization";
    private static final String TOKEN_PREFIX = "Bearer ";

    public static BaseUser getUserInfo(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            BaseUser user = new BaseUser();
            user.setUserId(jwt.getClaim("userId").asString());
            user.setCompanyId(jwt.getClaim("companyId").asString());
            user.setFactoryId(jwt.getClaim("factoryId").asString());
            return user;
        } catch (JWTDecodeException e) {
            return null;
        }
    }


    public static String extractToken(HttpServletRequest request) {
        String bearerToken = request.getHeader(AUTH_HEADER);
        if (bearerToken != null && bearerToken.startsWith(TOKEN_PREFIX)) {
            return bearerToken.substring(TOKEN_PREFIX.length());
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(getUserInfo("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb21wYW55SWQiOiIxMDAwMDAwMDEiLCJpc3MiOiJhdXRoMCIsImV4cCI6MTcyODYxMTk5NywidXNlcklkIjoiMTEwMDAwMTk3MTAxMDEwMDAwIn0.ZlKMmrDKQiU1PTxseg0qCu5Bb2LwZryBr72C9XxWpHs"));
    }
}
